package com.abu.ucenter.service.impl;

import com.abu.exceptionhandler.EduException;
import com.abu.ucenter.pojo.Member;
import com.abu.ucenter.mapper.MemberMapper;
import com.abu.ucenter.pojo.RegisterVo;
import com.abu.ucenter.service.MemberService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author 阿布
 * @since 2020-06-21
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Resource
    private MemberMapper memberMapper;

    private static final String PREFIX = "MEMBER.REGISTER.";

    /**
     * 用户注册
     *
     * @param registerVo
     * @return
     */
    @Override
    public Boolean register(RegisterVo registerVo) {
//        1.根据手机号获取缓存中的验证码
//        判断手机号是否已经存在
        Member fromMember = this.getOne(new QueryWrapper<Member>().eq("mobile", registerVo.getMobile()));
        if (fromMember != null) {
            return false;
        }
        String code = this.redisTemplate.opsForValue().get(PREFIX + registerVo.getMobile());
        if (StringUtils.isBlank(code)) {
            throw new EduException(20001, "获取验证码失败");
        }
//        2.比较验证码
        if (!StringUtils.equals(code, registerVo.getCode())) {
            throw new EduException(20001, "验证码不一致");
        }
//        3.对密码加盐加密(这里使用BCrpyt进行加盐加密)
        String encodePassword = this.passwordEncoder.encode(registerVo.getPassword());
//        4.添加用户数据到数据库中
        Member member = new Member();
        member
                .setMobile(registerVo.getMobile())
                .setPassword(encodePassword)
                .setNickname(registerVo.getNickname())
                .setAvatar("https://abu-edu.oss-cn-beijing.aliyuncs.com/2020-06-17/2bda122fe5b54e7ea2741b0ea0b272a5·file.png")
                .setSex(1)
                .setSign("无");
        boolean flag = this.save(member);
//        保存用户后删除验证码
        this.redisTemplate.delete(PREFIX + registerVo.getMobile());
        return flag;
    }

    @Override
    public Integer queryCount(String date) {
        return this.memberMapper.queryByDate(date);
    }
}
